<?php

namespace app\controllers\h5\mini;

use app\controllers\h5\base\H5Controller;
use app\controllers\wx\services\Wx;
use app\models\Red;
use app\models\system\SetQrcode;
use app\models\system\SetWx;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\UserBalance;
use app\util\Qrcode;
use app\util\Request;
use yii\imagine\Image;

class MiniQrcodeController extends H5Controller
{
    public function actionGetQrcode()
    {
        $set = SetWx::getLastOne(false);

        $scene = $this->post('scene', $this->user->id);
        // 页面 page，例如 pages/index/index，根路径前不要填加 /
        // $page = $this->post('page', 'sub_main/pages/user/login/index');

        $base = \Yii::$app->getBasePath();
        $path = $base . '/web/qrcode/referrer/' . $scene . '.png';
        // $path = $base . '/web/qrcode/referrer/' . $scene . '.jpg';

        if (!file_exists($path)) {
            // get
            // $getAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$set->app_id}&secret={$set->app_secret}";
            // $result = Request::get($getAccessToken);
            $access_token = Wx::getAccessToken();

            // post
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
            // $result = Request::post($url, json_encode(['scene' => $scene, 'page' => $page]));
            $result = Request::post($url, json_encode(['scene' => $scene, 'width' => 600]));
            // $result = Request::post($url, json_encode(['scene' => $scene, 'width' => 280, 'is_hyaline' => true]));

            // todo 这里token可能过期

            // var_dump($result);exit;

            $dir = dirname($path);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
                chmod($dir, 0777);
            }

            // wx qrcode
            file_put_contents($path, $result);

            // sleep(1);
        }

        // list
        $list = [];
        $name = '/qrcode/referrer/' . $scene . '.png';
        // $name = '/qrcode/referrer/' . $scene . '.jpg';

        // var_dump($path);exit;

        // if (file_exists($path)) {
        //     Image::thumbnail(
        //         $path,
        //         120,
        //         120
        //     )->save($path, ['quality' => 100]);
        // }

        $set = SetQrcode::getLastOne();
        // $nickname = User::find()
        //     ->where(['id' => $this->user->id])
        //     ->select(['nickname'])
        //     ->scalar();
        // if ($nickname) {
        //     $nickname = base64_decode($nickname);
        // } else {
        //     $nickname = '';
        // }
        // $length = 4;
        // if (mb_strlen($nickname) > $length) {
        //     $nickname = mb_substr($nickname, 0, $length) . '...';
        // }

        if ($set['images'] && count($set['images']) > 0) {
            foreach ($set['images'] as $item) {

                // var_dump($item);exit;

                $poster = $item['path'];
                $real = '/qrcode/referrer/' . $scene . '-' . $item['id'] . '.png';
                // $real = '/qrcode/referrer/' . $scene . '-' . $item['id'] . '.jpg';
                // Qrcode::setPoster($name, $poster, $real, [43, 285]);


                // 这里用了缩小, 并且处理了 位置 (375 - 120) / 2
                Qrcode::setPoster($name, $poster, $real, [205, 750], [340, 340]);

                // 文字
                // Qrcode::setText($real, $nickname, '', [305, 660], 12, '#ff0000');
                Qrcode::setText($real, 'ID:' . $this->user->id, '', [320, 1110], 20,'#000000');

                array_push($list, $real);
            }
        }

        $data = [
            'list' => $list,
            'id' => $scene,
        ];

        return $this->successEncode($data);
    }


    // 生成红包码
    public static function actionRed( Red $red)
    {

        // $scene = $this->post('scene', 1);
        // 页面 page，例如 pages/index/index，根路径前不要填加 /
        // 并且页面要发布才行, 所以到首页, 然后跳转
        // $page = $this->post('page', 'pages/red/index');
        // $page = $this->post('page', 'pages/home/index');


        $scene = 'red-' . $red->id;
        $page = 'pages/home/index';

        $base = \Yii::$app->getBasePath();
        $path = $base . '/web/qrcode/red/' . $red->id . '.png';

        if (!file_exists($path)) {
            // get
            // $getAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$set->app_id}&secret={$set->app_secret}";
            // $result = Request::get($getAccessToken);
            $access_token = Wx::getAccessToken();

            // post
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
            // $result = Request::post($url, json_encode(['scene' => $scene, 'page' => $page, 'width' => 280, 'is_hyaline' => true]));
            $result = Request::post($url, json_encode(['scene' => $scene, 'page' => $page, 'width' => 280]));

            // todo 这里token可能过期

            // var_dump($result);exit;

            $dir = dirname($path);
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
                chmod($dir, 0777);
            }

            // wx qrcode
            file_put_contents($path, $result);

            // sleep(1);

            // Image::thumbnail(
            //     $path,
            //     100,
            //     100
            // )->save($path, ['quality' => 100]);
        }

    }

    // 领取红包
    public function actionSaveRed()
    {
        $id = $this->post('id');
        $red = Red::findOne(['id' => $id]);
        if (!$red) {
            return $this->fail('红包已过期');
        }
        if ($red->status == 1) {
            return $this->fail('红包已被领取');
        }

        $red->status = 1;
        $red->user_id = $this->user->id;
        $red->save();


        $model = new UserCommission();
        $model->user_id = $this->user->id;
        $model->fans_id = 0;
        $model->order_id = 0;
        $model->balance = $red->amount;
        $model->status = 1;
        $model->award_name = '红包';
        $model->award_type = '222';
        $model->save();

        $account = UserAccount::findOne(['user_id' => $this->user->id]);
        if ($account) {

            // balance logs
            UserBalance::addLog($this->user->id,
                $account->balance, $red->amount, $account->balance + $red->amount, '红包');


            $account->balance += $red->amount;
            $account->save();
        }


        return $this->successEncode(['red' => $red->toArray()]);
    }
}